<template>
  <div>
    <el-drawer
      title="prompt"
      :visible.sync="dialogVisible"
      :wrapper-closable="false"
      class="mt-dialog"
      append-to-body
      size="80%"
      @close="close"
    >

      <div class="top">
        <el-select v-model="all" placeholder="选择种类" filterable>
          <el-option
            label="全公司"
            value="company"
          />
          <el-option
            label="我创建的"
            value="mine"
          />
          <el-option
            label="系统创建"
            value="system"
          />
        </el-select>
        <el-select v-model="app" placeholder="使用场景" filterable clearable>
          <el-option
            v-for="category in apps"
            :key="category.label"
            :label="category.label"
            :value="category.value"
          />
        </el-select>
        <el-input
          v-model="kwInput"
          placeholder="输入 任意字符 进行筛选"
          class="input-with-select"
          clearable
          style="width: 300px;"
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
        <el-button
          type="primary"
          class="el-icon-plus add-btn"
          :disabled="listLoading"
          @click="handleAction('create', '添加')"
        >添加
        </el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="data"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @sort-change="handleSort"
      >

        <el-table-column align="center" width="100" prop="id" label="ID" sortable="custom" />

        <el-table-column align="center" label="名称" prop="name" sortable="custom" width="200">
          <template slot-scope="scope">
            <span :title="scope.row.name">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="全局规则" prop="is_rule" sortable="custom" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_rule"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="用于" prop="app" sortable="custom" width="180">
          <template slot-scope="scope">
            <span :title="scope.row.app">{{ scope.row.app }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="prompt" prop="prompt" sortable="custom">
          <template slot-scope="scope">
            <el-input v-if="!scope.row.global_public" v-model="scope.row.prompt" type="textarea" :rows="6" />
            <el-tag v-else>系统创建不可修改</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="性质" prop="is_rule" sortable="custom" width="180">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.global_public" type="danger">系统预设</el-tag>
            <el-tag v-else-if="scope.row.company_public" type="success">公司公共</el-tag>
            <el-tag v-else>个人</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="系统参数" prop="is_rule" sortable="custom" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.global_public"
              disabled
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="handleAction('shortcode', scope.row)">ShortCode</el-button>
            <el-button v-if="!scope.row.global_public" size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
            <el-button v-if="!scope.row.global_public" size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />

      <el-dialog
        append-to-body
        :title="title"
        :width="width"
        :visible.sync="innerDialogVisible"
        :close-on-click-modal="false"
      >
        <el-form :model="temp" label-position="left" label-width="80px">

          <el-form-item v-if="action !== 'delete'" label="名称">
            <el-input v-model="temp.name" />
          </el-form-item>
          <el-form-item v-if="action !== 'delete'" label="应用于">
            <el-select v-model="temp.app" placeholder="应用于" class="head" filterable @change="handleAppChange">
              <el-option
                v-for="category in apps"
                :key="category.label"
                :label="category.label"
                :value="category.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="action !== 'delete'" label="prompt">
            <el-input v-model="temp.prompt" type="textarea" :rows="5" placeholder="prompt" />
            <el-alert>
              {{ tips }}
            </el-alert>
          </el-form-item>
          <el-form-item v-if="action !== 'delete'" label="提示">
            <el-input v-model="temp.placeholder" />
          </el-form-item>
          <el-form-item label="默认模型">
            <el-select v-model="temp.engine" placeholder=" " size="mini" filterable clearable>
              <el-option v-for="item in ai_engines" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="!temp.global_public" label="公司公共">
            <el-switch
              v-model="temp.company_public"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
          <el-form-item v-if="action !== 'delete'" label="全局规则">
            <el-switch v-model="temp.is_rule" active-color="#13ce66" inactive-color="#ff4949" />
          </el-form-item>
          <el-form-item label="系统参数">
            <el-switch
              v-model="temp.global_public"
              active-color="#13ce66"
              :disabled="this.$store.getters.roles.indexOf('super_admin') === -1"
              inactive-color="#ff4949"
            />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="innerDialogVisible = false">取 消</el-button>
          <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
    </el-drawer>
    <el-dialog
      append-to-body
      :title="'ShortCode'"
      :visible.sync="shortcodeVisible"
      @close="shortcodeVisible = false"
    >
      使用模型:<el-select v-model="engine" placeholder=" " size="mini" filterable clearable @change="handleGenerateShortCode">
        <el-option v-for="item in ai_engines" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-input v-model="showrt_code" :rows="5" placeholder="shortcode" />
      <el-button type="primary" @click="copyShortCode">复制</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/cms/aiprompt'

import qs from 'qs'
import { aiprompt_apps } from '../../../api/crm/crmcommon'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Aiprompt',
  props: ['isVisible'],
  data() {
    return {
      tips: '使用{{xxx}}作为动态参数会被替换，例如：{{name}}',
      ai_engines: [
        {
          label: 'GTP4omini',
          value: 'gpt-4o-mini'
        },
        {
          label: 'GTP 4o',
          value: 'gpt-4o'
        },
        {
          label: '通义千问',
          value: 'qwen_turbo'
        },
        {
          label: 'GTP 4(很贵,慎用)',
          value: 'gpt-4'
        }
      ],
      data: [],
      app: '',
      engine: 'gpt-4o-mini',
      showrt_code: '',
      listLoading: true,
      all: 'company',
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      shortcodeVisible: false,
      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        name: '',
        engine: 'gpt-4o',
        placeholder: '请直接输入内容',
        is_rule: false,
        prompt: '',
        app: 'content',
        company_public: true,
        global_public: false
      },
      apps: aiprompt_apps,
      width: '',

      innerDialogVisible: false
    }
  },
  watch: {
    isVisible(v) {
      this.dialogVisible = v
      if (v) {
        this.getList()
      }
    }
  },
  methods: {
    handleAppChange(v) {
      // 从apps中获取对应的tips
      this.tips = this.apps.find(item => item.value === v).tips
    },
    copyShortCode() {
      this.$copyText(this.showrt_code).then(() => {
        this.$message({
          message: '复制成功',
          type: 'success'
        })
        this.shortcodeVisible = false
        this.$emit('insert', this.showrt_code)
      }, () => {
        this.$message({
          message: '复制失败',
          type: 'error'
        })
      })
    },
    handleGenerateShortCode(v) {
      this.showrt_code = `[aiwriter engine="${v}" id="${this.temp.id}" name="${this.temp.name}"]`
    },
    resetTemp() {
      this.temp = {
        name: '',
        prompt: '',
        engine: 'gpt-4o',
        is_rule: false,
        app: '',
        company_public: true,
        global_public: false
      }
    },
    getList() {
      console.log(this.$store.getters.roles)
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        all: this.all,
        app: this.app,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
          this.ai_engines = response.data.ai_engines
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'shortcode':
          this.temp = row
          this.shortcodeVisible = true
          this.handleGenerateShortCode(this.engine)
          break
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.name}?`
          this.temp = row
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改${row.name}`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          Post(this.temp).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
          })
          break
        case 'delete':
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case 'edit':
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeDialog', false)
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin-top: 60px;
    /*margin: 168px auto !important;*/
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
  }
</style>
